<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Models\Knowledge;
use App\Models\KnowledgeCategory;
use App\Utils\FileUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Controller;

class KnowledgeController extends Controller
{
    /**
     * 知识列表（带分类关联和搜索）
     * GET /api/teacher/knowledges
     */
    public function index(Request $request)
    {
        // 请求参数
        $title = $request->input('title');
        $categoryId = $request->input('category_id');
        $status = $request->input('status', 1);
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        // 查询当前教师的知识
        // $query = Knowledge::with('category:id,name') // 关联分类
        //                 ->where('teacher_id', auth('admin')->id());
        
        $query = Knowledge::with('category:id,name');
        $query->where('is_wps', '0');
        // 搜索条件
        if (!empty($title)) {
            $query->where('title', 'like', "%{$title}%");
        }
        if (!empty($categoryId)) {
            $query->where('category_id', $categoryId);
        }
        if (isset($status)) {
            $query->where('status', $status);
        }

        // 分页
        $knowledges = $query->paginate($pageSize, ['*'], 'page', $page);

        return $this->paginated($knowledges->items(), $knowledges);
    }

    /**
     * 分类列表（带搜索）
     * GET /api/teacher/knowledge-categories
     */
    public function categoryList(Request $request)
    {
        $name = $request->input('name');
        $query = KnowledgeCategory::where('status', 1); // 只显示正常分类

        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }

        $categories = $query->get();
        return $this->success($categories);
    }

    /**
     * 新增/编辑知识
     * POST/PUT /api/teacher/knowledges
     */
    public function save(Request $request)
    {
        // 验证参数
        $request->validate([
            'id' => 'nullable|integer|exists:knowledges,id',
            'category_id' => 'nullable|integer|exists:knowledge_categories,id',
            'category' => 'required_if:category_id,null|string|max:50',
            'title' => 'required|string|max:100',
            'type' => 'required|in:1,2,3', // 1pdf 2视频 3三方链接
            'file_url' => 'nullable|array', // 仅1/2类型需要，数组格式
            'third_party_link' => 'nullable|url', // 仅3类型需要
            'status' => 'boolean'
        ]);

        $type = $request->input('type');
        $data = $request->only(['title', 'type', 'status']);

        // 处理分类逻辑
        $categoryId = $request->input('category_id');
        $teacherId = auth('admin')->id();
        if (empty($categoryId)) {
            // 如果category_id为空，则创建新分类
            $category = KnowledgeCategory::create([
                'name' => $request->input('category'),
                'status' => 1
            ]);
            $data['category_id'] = $category->id;
        } else {
            // 如果category_id不为空，则使用传入的category_id
            $data['category_id'] = $categoryId;
        }

        // 验证文件类型与知识类型一致性
        if ($type === 1 || $type === 2) {
            // 1(PDF)/2(视频)必须有文件URL，且不能有三方链接
            if (empty($request->input('file_url'))) {
                return $this->error('请上传文件', 422);
            }
            if (!empty($request->input('third_party_link'))) {
                return $this->error('该类型不支持三方链接', 422);
            }
            $data['file_url'] = json_encode($request->input('file_url')); // 转为JSON存储
            $data['third_party_link'] = null;
        } elseif ($type === 3) {
            // 3(三方链接)必须有链接，且不能有文件
            if (empty($request->input('third_party_link'))) {
                return $this->error('请填写三方链接', 422);
            }
            if (!empty($request->input('file_url'))) {
                return $this->error('该类型不支持上传文件', 422);
            }
            $data['third_party_link'] = $request->input('third_party_link');
            $data['file_url'] = null;
        }
        $data['teacher_id'] = $teacherId;

        // 新增或更新
        $knowledge = Knowledge::updateOrCreate(
            ['id' => $request->input('id')],
            $data
        );

        $message = $request->input('id') ? '更新成功' : '创建成功';
        return $this->success($knowledge, $message);
    }

    /**
     * 文件上传（支持多文件）
     * POST /api/teacher/knowledge-upload
     */
    public function upload(Request $request)
    {
        $request->validate([
            'type' => 'required|in:1,2', // 1=PDF 2=视频
            'files' => 'required|array',
            'files.*' => 'file|max:102400' // 限制单文件100MB
        ]);

        try {
            // 调用工具类上传
            $fileType = $request->input('type') == 1 ? 'pdf' : 'video';
            $urls = FileUpload::uploadMultiple($request->file('files'), $fileType);

            $data = [
                'file_urls' => $urls, // 返回URL数组
                'file_urls_json' => json_encode($urls) // 同时返回JSON字符串
            ];
            
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 422);
        }
    }
}
